<template>
    <video :src="src" autoplay loop muted disablePictureInPicture class="lazy-video"></video>
</template>

<script setup lang="ts" name="VideoView">

defineProps<{src: string}>()

document.addEventListener('DOMContentLoaded', () => {
  // 获取所有需要懒加载的视频
  const videos: NodeListOf<HTMLVideoElement> = document.querySelectorAll('.lazy-video');

  // 配置 Intersection Observer
  const observerOptions: IntersectionObserverInit = {
    root: null, // 相对于视口
    rootMargin: '0px', // 无额外边距
    threshold: 0.5, // 当 50% 的视频进入视口时触发
  };

  // 回调函数
  const observerCallback: IntersectionObserverCallback = (entries, observer) => {
    entries.forEach((entry) => {
      const video = entry.target as HTMLVideoElement;

      if (entry.isIntersecting) {
        // 视频进入视口，动态设置视频源并播放
        if (!video.src) {
          video.src = video.dataset.src || '';
        }
        video.play().catch((error) => {
          console.error('视频播放失败:', error);
        });
      } else {
        // 视频离开视口，暂停视频
        video.pause();
      }
    });
  };

  // 创建 Intersection Observer 实例
  const observer = new IntersectionObserver(observerCallback, observerOptions);

  // 监听每个视频
  videos.forEach((video) => {
    observer.observe(video);
  });
});

</script>

<style scoped>

video {
    width: 50%;
    border-radius: 10px;
    transition: transform 0.3s ease;
}

video:hover {
    box-shadow: 0 0 5px lightgray;
    transform: scale(1.02);
}

</style>